<template>
  <Modal v-model:visible="showModal" title="新生儿概况" width="1000px">
    <div class="flex flex-col w-full">
      <a-tabs v-model:activeKey="activeKey" size="small">
        <a-tab-pane key="1" tab="基本信息"></a-tab-pane>
        <a-tab-pane key="2" tab="区域占比"></a-tab-pane>
      </a-tabs>

      <div class="flex flex-row items-center mb-1">
        <a-select
          v-model:value="searchParams.year"
          :options="utils.genSelectOptions('year')"
          @change="loadData"
        ></a-select>

        <a-select
          class="ml-1"
          v-model:value="searchParams.quarter"
          :options="utils.genSelectOptions('quarter')"
          @change="loadData"
        ></a-select>
      </div>

      <div v-show="activeKey === '1'">
        <vxe-table
          :loading="true"
          v-bind="customTableStyle"
          :data="tableData"
          class="custom-vxe-table"
        >
          <vxe-column field="year" title="年份" width="80">
            <template #default="{ row }"> {{ row.year || 0 }}年 </template>
          </vxe-column>
          <vxe-column field="quarter" title="季度" width="80">
            <template #default="{ row }"> {{ row.quarter || 0 }}季度 </template>
          </vxe-column>
          <!--          <vxe-column field="index" title="总人数排名" width="100">-->
          <!--            <template #default="{ row }">-->
          <!--              {{ row.index || 0 }}-->
          <!--            </template>-->
          <!--          </vxe-column>-->
          <vxe-column field="name" title="街道名称" minWidth="120">
            <template #default="{ row }">
              {{ row.name || '未知' }}
            </template>
          </vxe-column>
          <vxe-column field="boyCount" title="男孩数量(人)" width="120" :sortable="true">
            <template #default="{ row }"> {{ row.boyCount || 0 }} </template>
          </vxe-column>
          <vxe-column field="girlCount" title="女孩数量(人)" width="120" :sortable="true">
            <template #default="{ row }"> {{ row.girlCount || 0 }}</template>
          </vxe-column>
          <vxe-column field="totalCount" title="总人数(人)" width="120" :sortable="true">
            <template #default="{ row }"> {{ row.totalCount || 0 }} </template>
          </vxe-column>
          <vxe-column field="boyPercentage" title="男孩占比" width="120" :sortable="true">
            <template #default="{ row }"> {{ row.boyPercentage || 0 }}% </template>
          </vxe-column>
          <vxe-column field="girlPercentage" title="女孩占比" width="120" :sortable="true">
            <template #default="{ row }"> {{ row.girlPercentage || 0 }}% </template>
          </vxe-column>
        </vxe-table>
      </div>

      <div
        v-show="activeKey === '2'"
        id="xsrgkByQyzb"
        class="w-[600px] mx-auto px-4 h-[50vh]"
      ></div>
    </div>
  </Modal>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import Modal from '@/components/modal.vue'
import { Apis } from '@/api'
import { message } from 'ant-design-vue'
import * as utils from '../../utils'
import * as echarts from 'echarts'

const isLoading = ref(false)

const activeKey = ref('1')

const showModal = ref(false)

const searchParams = ref({
  year: '',
  quarter: '',
})
const tableData = ref<any[]>([])

// 统一管理表格样式
const customTableStyle = {
  ...utils.customTableStyle,
  footerMethod: ({ columns, data }) => {
    const footerData = [
      columns.map((column, columnIndex) => {
        if (columnIndex === 0) {
          return '合计'
        }
        if (['boyCount', 'girlCount', 'totalCount'].includes(column.field)) {
          return (utils.sumNum(data, column.field) || '') + '人'
        }

        return ''
      }),
    ]
    return footerData
  },
}

function loadData() {
  isLoading.value = true

  loadDataByChart()

  Apis.szbt.newBorn
    .get_selectNewBornQyzb({
      params: {
        searchYear: searchParams.value.year,
        quarter: searchParams.value.quarter,
      },
    })
    .then((res) => {
      tableData.value = res
        .sort((a: any, b: any) => {
          // 先按年份倒序
          if (b.year !== a.year) {
            return b.year - a.year
          }

          return b.boyCount + b.girlCount - (a.boyCount + a.girlCount)
        })
        .map((item: any, index: number) => {
          item.index = index + 1
          const totalCount = (item.boyCount || 0) + (item.girlCount || 0)
          item.totalCount = totalCount
          item.boyPercentage = totalCount
            ? (((item.boyCount || 0) / totalCount) * 100).toFixed(2)
            : 0
          item.girlPercentage = totalCount
            ? (((item.girlCount || 0) / totalCount) * 100).toFixed(2)
            : 0
          return item
        })
    })
    .catch((err) => {
      message.error('获取数据失败')
    })
    .finally(() => {
      isLoading.value = false
    })
}

// 新生儿概况
const xsrgk = reactive({
  areas: [],
})

// 新生儿区域占比
const xsrgkByQyzbOptions = reactive({
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)',
    backgroundColor: 'rgba(0,0,0,0.7)',
    borderColor: 'rgba(255,255,255,0.3)',
    textStyle: {
      // color: '#fff',
      fontSize: 12,
    },
  },
  legend: {
    orient: 'horizontal',
    bottom: '0%',
    itemGap: 4, // 减小图例间距
    itemWidth: 10, // 减小图例标记的宽度
    itemHeight: 10, // 减小图例标记的高度
    textStyle: {
      fontSize: 10, // 减小图例文字大小
      color: '#f0f0f0',
    },
  },
  series: [
    {
      name: '区域占比',
      type: 'pie',
      radius: '50%',
      data: xsrgk.areas.map((area) => ({
        value: area.boyCount + area.girlCount,
        name: area.name,
      })),
      label: {
        show: false, // 关闭指示线
      },
      labelLine: {
        show: false, // 关闭指示线
      },
      color: [
        '#5470c6',
        '#91cc75',
        '#fac858',
        '#ee6666',
        '#73c0de',
        '#3ba272',
        '#fc8452',
        '#9a60b4',
        '#ea7ccc',
        '#48b3bd',
      ],
    },
  ],
})

/** 新生儿区域占比 */
function initsrgkByQyzbChart() {
  const chartDom = document.getElementById('xsrgkByQyzb')
  if (!chartDom) return
  let myChart = echarts.getInstanceByDom(chartDom)
  if (!myChart) {
    myChart = echarts.init(chartDom)
  }

  myChart.setOption(xsrgkByQyzbOptions, { notMerge: true })
}

async function loadDataByChart() {
  try {
    const { year, quarter } = searchParams.value
    let getNewBornQyzbRes = await Apis.szbt.newBorn.get_selectNewBornQyzb({
      params: {
        searchYear: year,
        quarter: quarter,
      },
    })

    getNewBornQyzbRes = getNewBornQyzbRes
      .map((item) => ({
        ...item,
        total: item.boyCount + item.girlCount,
      }))
      .sort((a, b) => b.total - a.total)

    xsrgkByQyzbOptions.title = {
      ...utils.generateChartTitle(utils.numberToChinese(quarter) + '季度新生儿区域占比'),
      top: '10%',
      textStyle: {
        fontSize: 14,
        color: '#f8f8f8',
      },
    }

    const areaNames = getNewBornQyzbRes.map((item) => item.name)
    const halfLength = Math.ceil(areaNames.length / 2) // 向上取整,优先放在左边

    xsrgkByQyzbOptions.legend = [
      {
        orient: 'vertical', // 垂直排列
        left: 'left', // 图例放在左侧
        top: 'middle', // 垂直居中
        data: areaNames.slice(0, halfLength), // 左侧显示前半部分
        itemGap: 4, // 减小图例间距
        itemWidth: 10, // 减小图例标记的宽度
        itemHeight: 14, // 减小图例标记的高度
        textStyle: {
          fontSize: 12, // 减小图例文字大小
          color: '#f0f0f0',
        },
        formatter: function (name) {
          const data = getNewBornQyzbRes.slice(0, halfLength)
          const item = data.find((d) => d.name === name)
          const index = data.indexOf(item) + 1
          const total = getNewBornQyzbRes.reduce((sum, cur) => sum + cur.total, 0)
          const percentage = ((item.total / total) * 100).toFixed(1)
          return `${index}. ${name} (${item.total}人)`
        },
      },
      {
        orient: 'vertical', // 垂直排列
        right: 'right', // 图例放在右侧
        top: 'middle', // 垂直居中
        data: getNewBornQyzbRes.slice(halfLength), // 右侧显示后半部分
        itemGap: 4, // 减小图例间距
        itemWidth: 10, // 减小图例标记的宽度
        itemHeight: 14, // 减小图例标记的高度
        textStyle: {
          fontSize: 12, // 减小图例文字大小
          color: '#f0f0f0',
        },
        formatter: function (name) {
          const data = getNewBornQyzbRes.slice(halfLength)
          const item = data.find((d) => d.name === name)
          const index = halfLength + data.indexOf(item) + 1
          const total = getNewBornQyzbRes.reduce((sum, cur) => sum + cur.total, 0)
          const percentage = ((item.total / total) * 100).toFixed(1)
          return `${index}. ${name} (${item.total}人)`
        },
      },
    ]
    xsrgkByQyzbOptions.series[0].data = getNewBornQyzbRes.map((item) => ({
      value: item.boyCount + item.girlCount,
      name: item.name,
    }))

    xsrgkByQyzbOptions.series[0].data = xsrgkByQyzbOptions.series[0].data

    initsrgkByQyzbChart()
  } catch (error) {}
}
defineExpose({
  setData: (data: any) => {
    const { params } = data
    searchParams.value = params
    // tableData.value = data;
  },
  open: () => {
    showModal.value = true
    loadData()

    setTimeout(() => {
      loadDataByChart()
    }, 200)
  },
})
</script>

<style lang="scss" src="@/styles/custom-vxe-table.scss"></style>
